#!/usr/bin/env python3
"""
This file is part of the Stargate project, Copyright Stargate Team

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 3 of the License.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
"""

import argparse
import json
import os

if not os.getuid() == 0:
    print("Error, this must be run as root.  Use su or sudo")
    exit(1)

choices = {
    "gnome": (
        "/usr/share/spin-kickstarts/fedora-live-workstation.ks",
        "Gnome",
    ),
    "lxde": (
        "/usr/share/spin-kickstarts/fedora-live-lxde.ks",
        "LXDE",
    ),
    "xfce": (
        "/usr/share/spin-kickstarts/fedora-live-xfce.ks",
        "XFCE",
    ),
    "kde": (
        "/usr/share/spin-kickstarts/fedora-live-kde.ks",
        "KDE",
    ),
    "mate": (
        "/usr/share/spin-kickstarts/fedora-live-mate_compiz.ks",
        "Mate",
    ),
}

try:
    import dnf
    db = dnf.dnf.Base()
    releasever = db.conf.substitutions['releasever']
except Exception as ex:
    print("Could not read dnf database, setting default releasever=33")
    print(ex)
    releasever = "34"

def parse_args():
    parser = argparse.ArgumentParser(
        description=(
            "Generate a Fedora based live distro image with Stargate"
            "pre-installed"
        )
    )
    parser.add_argument(
        "--de",
        choices=sorted(choices.keys()),
        default="kde",
        help="The desktop environment, (default: kde)",
    )
    parser.add_argument(
        '--releasever',
        default=releasever,
        help="The release of Fedora to base the OS image on.  Default: {}".format(
            releasever
        ),
    )
    return parser.parse_args()

args = parse_args()

ks_file, de_label = choices[args.de]

if not os.path.exists(ks_file):
    print(
        "{} not found, please run "
        "'sudo dnf install spin-kickstarts'".format(
            ks_file,
        )
    )
    print(
        "If spin-kickstarts is already installed, Fedora may have changed "
        "the file name or removed it in a recent release"
    )
    exit(1)

os.system("setenforce 0")

dirname = os.path.dirname(__file__)
with open(
    os.path.join(dirname, '..', 'src', 'meta.json'),
) as f:
    j = json.load(f)
    global_version = j['version']['major']
    version = j['version']['minor']

rpm_file = None

global_rpm_dir = os.path.abspath(
    os.path.join(
        dirname,
        '..',
    )
)

rpm_file = None

for f_rpm_file in os.listdir(global_rpm_dir):
    if f_rpm_file.startswith(global_version) and \
    f_rpm_file.endswith(".rpm") and \
    version in f_rpm_file and \
    "debuginfo" not in f_rpm_file:
        rpm_file = f_rpm_file
        print("Using {}".format(rpm_file))

if rpm_file is None:
    print("No Stargate .rpm files with current version {} found in {}, \n"
        "please run the following commands before running this script:".format(
        version, global_rpm_dir))
    print("\n\ncd ..")
    print("./rpm.py")
    print("cd fedora")
    exit(1)

rpm_file = open("{}/{}".format(global_rpm_dir, rpm_file), "rb")
rpm_bytes = rpm_file.read()
rpm_file.close()

kickstart_template = \
"""#kickstart file for Stargate-OS-Fedora, generated by {script_path}

%include {ks_file}

%packages

#Stargate Dependencies
alsa-lib-devel
fftw-devel
lame
libsndfile-devel
portaudio-devel
portmidi-devel
python3-devel
python3-numpy
python3-qt5
rubberband
vorbis-tools

#Not actually dependencies, but giving people with Firewire devices
#a fighting chance of being able to use the live DVD/USB after an excessive
#amount of configuration
ffado
qjackctl

%end

%post

sed -i s/SELINUX=enforcing/SELINUX=disabled/g /etc/selinux/config

%end

%post --interpreter /usr/bin/python3

# embed the Stargate rpm file into the kickstart template, to subvert the
# need to setup a Yum repository somewhere on the internet, or worry about DNS

import os

my_rpm_file = open("/tmp/stargate.rpm", "wb")
my_rpm_file.write({rpm_bytes})
my_rpm_file.close()

os.system("rpm -ivh /tmp/stargate.rpm")

%end
""".format(
    script_path=os.path.abspath(__file__),
    ks_file=ks_file,
    rpm_bytes=str(rpm_bytes),
)

kickstart_file = open("kickstart.ks", "w")
kickstart_file.write(kickstart_template)
kickstart_file.close()

#TODO:  Maybe use --base-on=live-cd.iso and then run yum update ?
#Or automate a chroot into tmpdir afterwards?

kickstart_command = """\
livecd-creator \
--verbose \
--config=./kickstart.ks \
--fslabel=Stargate-OS-Fedora \
--cache=cache/live \
--releasever={releasever} \
""".format(
    releasever=args.releasever,
)
print(kickstart_command)
os.system(kickstart_command)

fname = "Stargate-OS-{}-Fedora-{}-{}.iso".format(
    version,
    args.releasever,
    de_label,
)
os.system(
    'mv Stargate-OS-Fedora.iso {}'.format(fname)
)

#os.system("setenforce 1")
